package com.ck.datacenter.log.aop;

import com.ck.datacenter.log.annotation.CkOperatedLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * TODO
 *
 * @author chenke
 * @version 1.0
 * @date 2021-12-24 11:45
 */
@Aspect
@Component
public class OperatedLogAspect {

    @Pointcut("@annotation(com.ck.datacenter.log.annotation.CkOperatedLog)" + "&&"
            + "execution(* com..controller.*.*(..))")
    public void annotation() {
    }

    @Around("annotation()")
    public Object aroundMethod(ProceedingJoinPoint pjd) throws Throwable {
        addLog(pjd);
        return pjd.proceed();
    }

    private void addLog(ProceedingJoinPoint pjd) {
        try {
            MethodSignature methodSignature = (MethodSignature) pjd.getSignature();
            // 获取所有参数
            Object[] args = pjd.getArgs();
            // 获取参数别名
            String[] parameterNames = methodSignature.getParameterNames();
            Method method = methodSignature.getMethod();
            CkOperatedLog annotation = method.getAnnotation(CkOperatedLog.class);

            String spelString = annotation.param();
            String module = annotation.module();
            String operation = annotation.operation();
            String description = annotation.description();

            // 参数经过spel表达式转换后值
            String paramStr = SpelUtil.parseSpEL(spelString, args, parameterNames);

            System.out.println("模块:" + module + ",操作:" + operation + ",描述:" + description + ",参数:" + paramStr);

            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            System.out.println("请求地址:" + request.getRequestURL().toString());

            // 再获取用户登录信息

            // 发送给MQ,然后进行落库
        } catch (Exception e) {
            System.out.println("捕获异常，防止影响业务方法");
        }
    }

}

